package com.example.flowabledemo.config.auth;

import com.alibaba.fastjson.JSONObject;
import com.example.flowabledemo.common.HttpCode;
import com.example.flowabledemo.data.pojo.SecUser;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description 用户登录成功时返回给前端的结果
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
  @Override
  public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code", HttpCode.OK);
    jsonObject.put("message", "登录成功！");
    //登录后，返回原访问页面
    RequestCache cache = new HttpSessionRequestCache();
    SavedRequest savedRequest = cache.getRequest(httpServletRequest, httpServletResponse);
    String url = "0";
    try {
      url = savedRequest.getRedirectUrl();
    } catch (Exception e) {
      url = "/";
    }
    jsonObject.put("url", url);
    //重新存储user对象到session
    SecUser securityUser = (SecUser) authentication.getPrincipal();
    System.out.println(securityUser);
    System.out.println(securityUser.getUsername());
    System.out.println(authentication.getAuthorities());
    System.out.println(authentication.getDetails());
    System.out.println(authentication.getPrincipal());
    System.out.println(authentication.getPrincipal());
//    httpServletRequest.getSession().setAttribute("user",oaUserMapper.getUserInfo(securityUser.getUsername()));
    //让浏览器用utf8来解析返回的数据
    httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
    httpServletResponse.setCharacterEncoding("UTF-8");//防止中文乱码
    PrintWriter writer = httpServletResponse.getWriter();
    writer.write(jsonObject.toJSONString());
  }
}
